<template>
  <div class="article-container">
    <!-- 导航栏 -->
    <van-nav-bar
      class="page-nav-bar"
      left-arrow
      title="黑马头条"
      left-text="返回"
      @click-left="onClickLeft"
    ></van-nav-bar>
    <!-- /导航栏 -->

    <div class="main-wrap">
      <!-- 加载中 -->
      <div class="loading-wrap" v-if="loading">
        <van-loading color="#3296fa" vertical>加载中</van-loading>
      </div>
      <!-- /加载中 -->

      <!-- 加载完成-文章详情 -->
      <div class="article-detail" v-else-if="article.title">
        <!-- 文章标题 -->
        <h1 class="article-title">{{ article.title }}</h1>
        <!-- /文章标题 -->

        <!-- 用户信息 -->
        <van-cell class="user-info" center :border="false">
          <van-image
            class="avatar"
            slot="icon"
            round
            fit="cover"
            :src="article.aut_photo"
          />
          <div slot="title" class="user-name">{{ article.aut_name }}</div>
          <div slot="label" class="publish-date">
            {{ article.pubdate | relativeTime }}
          </div>
          <van-button
            v-if="article.is_followed"
            class="follow-btn"
            round
            size="small"
            @click="onFollow"
            :loading="isFollowLoading"
            >已关注</van-button
          >
          <van-button
            v-else
            class="follow-btn"
            type="info"
            color="#3296fa"
            round
            size="small"
            icon="plus"
            @click="onFollow"
            :loading="isFollowLoading"
            >关注</van-button
          >
        </van-cell>
        <!-- /用户信息 -->

        <!-- 文章内容 -->
        <div
          class="article-content article-content markdown-body"
          v-html="article.content"
          ref="contentRef"
        ></div>
        <van-divider>正文结束</van-divider>
        <!-- 底部区域 -->
        <!-- 文章评论 -->
        <article-comment
          :source="article.art_id"
          @onload-success="totalCount = $event"
          :list="commentList"
          @click-reply="onReplayclick"
        />
        <!-- /文章评论 -->
        <div class="article-bottom">
          <van-button
            class="comment-btn"
            type="default"
            round
            size="small"
            @click="isPostShow = true"
            >写评论</van-button
          >
          <van-icon name="comment-o" :info="totalCount" color="#777" />
          <!-- 点击收藏组件 -->
          <CollectArticle
            v-model="article.is_collected"
            :article_id="article.art_id"
          />
          <!-- <van-icon color="#777" name="star-o" /> -->
          <!-- <van-icon color="#777" name="good-job-o" /> -->
          <!-- 用户点赞组件 -->
          <likeArticle
            v-model="article.attitude"
            :article_id="article.art_id"
          />
          <!-- 用户点赞组件 -->
          <!-- 用户分享文章模块 -->

          <van-icon name="share" color="#777777" @click="showShare = true">
          </van-icon>
          <van-share-sheet
            v-model="showShare"
            title="立即分享给好友"
            :options="options"
            @select="onSelect"
          />

          <!-- 用户分享文章模块 -->
        </div>
        <!-- /底部区域 -->
        <van-popup v-model="isPostShow" position="bottom"
          ><CommentPost
            :target="article.art_id"
            @onpost-success="onPostSuccess"
          ></CommentPost>
        </van-popup>

        <!-- 评论回复 -->
        <van-popup v-model="isReplyShow" position="bottom" style="height: 100%">
          <CommentReply
            :comment="currentComment"
            @click-close="isReplyShow = false"
            v-if="isReplyShow"
          ></CommentReply>
        </van-popup>
      </div>

      <!-- /加载完成-文章详情 -->

      <!-- 加载失败：404 -->
      <div class="error-wrap" v-else-if="errStatus === 404">
        <van-icon name="failure" />
        <p class="text">该资源不存在或已删除！</p>
      </div>
      <!-- /加载失败：404 -->

      <!-- 加载失败：其它未知错误（例如网络原因或服务端异常） -->
      <div class="error-wrap" v-else>
        <van-icon name="failure" />
        <p class="text">内容加载失败！</p>
        <van-button class="retry-btn" @click="loadArtcileInfo"
          >点击重试</van-button
        >
      </div>
      <!-- /加载失败：其它未知错误（例如网络原因或服务端异常） -->
    </div>
  </div>
</template>

<script>
import { getArticleById } from "@/api/article.js";
import "./github-markdown.css";
import { ImagePreview } from "vant";
import { addFollow, deleteFollow } from "@/api/user";
import CollectArticle from "./components/collectArticle.vue";
import ArticleComment from "./components/article-comment";
import CommentPost from "./components/CommentPost.vue";
import CommentReply from "./components/comment-reply.vue";
import likeArticle from "./components/likeArticle.vue";

export default {
  name: "ArticleIndex",
  components: {
    CollectArticle,
    ArticleComment,
    CommentPost,
    CommentReply,
    likeArticle,
  },
  //使用路由解耦将动态参数映射到props中；
  props: {
    articleId: {
      type: [Number, String, Object],
      required: true,
    },
  },

  provide: function () {
    return { articleId: this.articleId };
  },

  data() {
    return {
      article: {}, // 文章详情
      loading: true,
      errStatus: 0,
      isFollowLoading: false,
      totalCount: 0,
      isPostShow: false,
      commentList: [],
      isReplyShow: false,
      currentComment: {}, // 点击回复的那个评论对象
      isShareShow: false,
      showShare: false,
      options: [
        [
          { name: "微信", icon: "wechat" },
          { name: "朋友圈", icon: "wechat-moments" },
          { name: "微博", icon: "weibo" },
          { name: "QQ", icon: "qq" },
        ],
        [
          { name: "复制链接", icon: "link" },
          { name: "分享海报", icon: "poster" },
          { name: "二维码", icon: "qrcode" },
          { name: "小程序码", icon: "weapp-qrcode" },
        ],
      ],
    };
  },
  computed: {},
  watch: {},
  created() {
    this.loadArtcileInfo();
  },
  mounted() {},
  methods: {
    async loadArtcileInfo() {
      this.loading = true;
      try {
        const { data } = await getArticleById(this.articleId);
        console.log("返回的数据是", data);

        // 模拟加载失败的随机现象
        // if (Math.random() > 0.5) {
        //   JSON.parse("154jkhjkbkjbjk");
        // }
        this.article = data.data;
        //使用定时器调用文章内容加载后的dom；因为真实dom是异步的；
        setTimeout(() => {
          this.previewImg();
        }, 0);
      } catch (err) {
        console.log(err);
        if (err.response && err.response.status === 404) {
          this.errStatus = 404;
        }
        this.$toast("获取失败");
      }
      // 加载完成
      this.loading = false;
    },
    onClickLeft() {
      //	点击左侧按钮时触发,使得路由返回；
      this.$router.back();
    },

    previewImg() {
      const contentEl = this.$refs.contentRef;
      const allImg = contentEl.querySelectorAll("img");
      console.log(allImg);
      const images = [];

      allImg.forEach((element, index) => {
        images.push(element.src);
        element.onclick = () => {
          ImagePreview({
            images, //images=images，es6简写方式；
            startPosition: index, //图片默认起始位置；
          });
        };
      });
    },

    // 用户关注模块

    async onFollow() {
      // 开启按钮的 loading 状态
      this.isFollowLoading = true;

      try {
        // 如果已关注，则取消关注
        const authorId = this.article.aut_id;
        if (this.article.is_followed) {
          await deleteFollow(authorId);
        } else {
          // 否则添加关注
          await addFollow(authorId);
        }

        // 更新视图
        this.article.is_followed = !this.article.is_followed;
      } catch (err) {
        let message = "操作失败了！";
        if (err.response && err.response.status === 400) {
          message = "不能关注自己！";
        }
        console.log(err);
        this.$toast.fail(message);
      }
      // 关闭按钮的 loading 状态
      this.isFollowLoading = false;
    },

    //评论弹层模块

    onPostSuccess(res) {
      console.log(res);
      this.commentList.unshift(res.data.data.new_obj);
      this.isPostShow = false;
    },
    onReplayclick(comment) {
      this.isReplyShow = true;
      this.currentComment = comment;
      console.log("发布评论的内容是", comment);
    },
    // 分享文章模块
    onSelect() {
      this.$toast("抱歉，该功能暂未开放！");
      this.showShare = false;
    },
  },
};
</script>

<style scoped lang="less">
.article-container {
  /deep/ .page-nav-bar {
    .van-nav-bar__content {
      .van-nav-bar__left {
        .van-icon {
          color: #fff;
        }
        .van-nav-bar__text {
          color: #fff;
        }
      }
    }
  }
  .main-wrap {
    position: fixed;
    left: 0;
    right: 0;
    top: 92px;
    bottom: 88px;
    overflow-y: scroll;
    background-color: #fff;
  }
  .article-detail {
    .article-title {
      font-size: 40px;
      padding: 50px 32px;
      margin: 0;
      color: #3a3a3a;
    }

    .user-info {
      padding: 0 32px;
      .avatar {
        width: 70px;
        height: 70px;
        margin-right: 17px;
      }
      .van-cell__label {
        margin-top: 0;
      }
      .user-name {
        font-size: 24px;
        color: #3a3a3a;
      }
      .publish-date {
        font-size: 23px;
        color: #b7b7b7;
      }
      .follow-btn {
        width: 170px;
        height: 58px;
      }
    }

    .article-content {
      padding: 55px 32px;
      /deep/ p {
        text-align: justify;
      }
    }
  }

  .loading-wrap {
    padding: 200px 32px;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #fff;
  }

  .error-wrap {
    padding: 200px 32px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    background-color: #fff;
    .van-icon {
      font-size: 122px;
      color: #b4b4b4;
    }
    .text {
      font-size: 30px;
      color: #666666;
      margin: 33px 0 46px;
    }
    .retry-btn {
      width: 280px;
      height: 70px;
      line-height: 70px;
      border: 1px solid #c3c3c3;
      font-size: 30px;
      color: #666666;
    }
  }

  .article-bottom {
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
    display: flex;
    justify-content: space-around;
    align-items: center;
    box-sizing: border-box;
    height: 88px;
    border-top: 1px solid #d8d8d8;
    background-color: #fff;
    .comment-btn {
      width: 282px;
      height: 46px;
      border: 2px solid #eeeeee;
      font-size: 30px;
      line-height: 46px;
      color: #a7a7a7;
    }
    .van-icon {
      font-size: 40px;
      .van-info {
        font-size: 16px;
        background-color: #e22829;
      }
    }
  }
}
</style>
